package shop.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import shop.IService;
import shop.model.City;
import shop.model.User;

import java.util.List;

@Controller
public class UserController {
    @Autowired
    private IService<City> cityService;
    @Autowired
    private IService<User> userService;
    @Autowired
    private User user;
    private User currentUser;
    private List<City> cities;

    public String createNewUser() {
        user.setEnabled("true");
        user.setRole("USER");
        userService.create(user);
        return "/registration.xhtml";
    }

    public User getCurrentUser() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String email = auth.getName();
        currentUser = userService.findByField("email", email);
        return currentUser;
    }

    public List<City> getCities() {
        if (cities == null) {
            cities = cityService.readAll();
            return cities;
        }
        return cities;
    }
}
